<?php

namespace wechat;

use think\Config;
use think\Db;

/**
 * 微信小程序类
 */
class Wx
{
    protected $appid = "wx012c4002f5a7fffa";
    protected $secret = "4c9e49d18d166021dd7e1b23d8f9f90f";

    //获取access_token
    public function getAccessToken()
    {

        $grant_type = 'client_credential';
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;

        $curl = new \Curl\Curl();
        $curl->get($url);
        $result = $curl->response;
        return $result;
    }

    /**
     * 获取小程序二维码
     * @param $order_sn
     * @param $send_user_id
     * @return bool|string  //二维码图片路径
     */
    public function getQrCode($send_user_id,$order_sn)
    {
        $accessTokenResult = $this->getAccessToken();
        $access_token = json_decode(json_encode($accessTokenResult), true);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token['access_token'];

        $curl = new \Curl\Curl();
        $page = "pages/open_presents/open_presents";
        $scene = $send_user_id . '-' . $order_sn;
        $curl->post($url, json_encode(['page' => $page, 'width' => 430, 'scene' => $scene]));
        $res = $curl->response;

//        file_put_contents('./log/log.php',date('Ymd H:i:s',time()) . json_encode($res) . PHP_EOL,FILE_APPEND);
        $result = json_decode(json_encode($res),true);

        if($result['errcode'] == 0){
            //存储图片
            $filepath = './uploads/qrcode/' . date('Ymd', time()) . time() . uniqid(rand(1000, 9999)) . '.jpg';
            file_put_contents($filepath, $res);

            return ['code' => 1, 'msg' => '', 'data' => substr($filepath, 1)];
        }else{
            return ['code' => 0, 'msg' => '生成二维码出错，错误码：' . $result['errcode'], 'data' => $result];
        }


    }



    /**
     *发送模板消息
     * $access_token
     * $params
     **/
    public function sendWxMsg($visitlog_id, $form_id)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
        $curl = new \Curl\Curl();
        $curl->get($url);
        $result = $curl->response;
        $access_token = json_decode(json_encode($result), true);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token['access_token'];
        $curl = new \Curl\Curl();
        $visitlog = \app\admin\model\Visitlog::get($visitlog_id);

        $openid = Db::name('user')->where('id', $visitlog['user_id'])->value('openid');
        $customer = \app\admin\model\Customer::get($visitlog['customer_id']);
        $jsonData = json_encode([
            'touser' => $openid,
            'template_id' => 'tN-0LU6X5gyB3yWUdD19WPQ5V5d6dZceFf4-lCgx97s',
            'page' => 'pages/soon/soon',
            'form_id' => $form_id,
            'data' => [
                'keyword1' => [
                    'value' => $customer['name'] . '-' . $customer['mobile'],
                    'color' => '#173177'
                ],
                'keyword2' => [
                    'value' => date('Y-m-d H:i'),
                    'color' => '#173177'
                ],
                'keyword3' => [
                    'value' => $customer['remark'],
                    'color' => '#173177'
                ]
            ]

        ]);

        $curl->post($url, $jsonData);
        $result = $curl->response;
        echo json_encode($result);

    }


}